package services

import (
	"errors"
	"login-server/config"
	"login-server/model"
	"login-server/utils"
	"time"
)

// 玩家注册
func Register(username, password, nickName string) error {
	var findUser model.User
	result := config.DB.Where("username = ?", username).First(&findUser)
	if result.RowsAffected > 0 {
		return errors.New("用户名已经存在")
	}

	hashPassword, err := utils.HashPassword(password)
	if err != nil {
		return errors.New("系统错误，请重试")
	}

	// 构建数据库
	user := model.User{
		Username:  username,
		Password:  hashPassword,
		NickName:  nickName,
		CreatedAt: time.Now(),
	}

	return config.DB.Create(&user).Error
}

// 玩家登录
func Login(username, password string) (*model.User, error) {
	var findUser model.User
	result := config.DB.Where("username = ?", username).First(&findUser)
	if result.Error != nil {
		return nil, errors.New("找不到用户")
	}

	if !utils.CheckPasswordHash(password, findUser.Password) {
		return nil, errors.New("密码错误")
	}

	return &findUser, nil
}
